//
//  URLDataRequester.m
//  Mehfile Zainab
//
//  Created by Sitara Badourali on 01/12/12.
//  Copyright (c) 2012 Sitara Badourali. All rights reserved.
//

#import "URLDataRequester.h"

const double MZURLCacheInterval = 120.0;

@implementation URLDataRequester

@synthesize dataPath;
@synthesize urlArray;
@synthesize filePath;
@synthesize fileDate;
@synthesize connection;

@synthesize viewController;
@synthesize news;

- (void) loadDataWithURL:(NSURL *)theURL
{
    
    [self startInitCache];
    
    //NSLog(@"Load new or existing cached data");
    
	[filePath release]; /* release previous instance */
	NSString *fileName = [[theURL path] lastPathComponent];
	filePath = [[dataPath stringByAppendingPathComponent:fileName] retain];
    //NSLog(@"Get the path to the cached data : %@",filePath);
    
	/* apply daily time interval policy */
    
	[self getFileModificationDate];
	/* get the elapsed time since last file update */
	NSTimeInterval time = fabs([fileDate timeIntervalSinceNow]);
	if (time > MZURLCacheInterval) {
		/* file doesn't exist or hasn't been updated for at least one day */
		self.connection = [[URLCacheConnection alloc] initWithURL:theURL delegate:self];
	}
	else {
		NSLog(@"Previously cached data found in cache and updated in last %f seconds.",MZURLCacheInterval);
        //[self endLoading];
	}
    
}

-(void)startInitCache {
    
    /* By default, the Cocoa URL loading system uses a small shared memory cache.
	 We don't need this cache, so we set it to zero when the application launches. */
    
    //NSLog(@"Turn off the NSURLCache shared cache");
    
    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0
                                                            diskCapacity:0
                                                                diskPath:nil];
    [NSURLCache setSharedURLCache:sharedCache];
    [sharedCache release];
    
	[self initCache];
    
}


- (void) initCache
{
    //NSLog(@"Prepare to use our own on-disk cache");
    
	/* create path to cache directory inside the application's Documents directory */
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    self.dataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MZCache"];
    
	//NSLog(@"Initializing cache, value of dataPath : %@",self.dataPath);
	
	/* check for existence of cache directory */
	if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
		return;
	}
    
	/* create a new cache directory */
	if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath
								   withIntermediateDirectories:NO
													attributes:nil
														 error:&error]) {
		NSLog(@"Error when creating on-disk cache directory : %@",error);
		return;
	}
}

/* get modification date of the current cached image */

- (void) getFileModificationDate
{
    
    NSLog(@"Check the last modified date of the data to see if we need to load a new version");
    
	/* default date if file doesn't exist (not an error) */
	self.fileDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
    
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
		/* retrieve file attributes */
		NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
		if (attributes != nil) {
			self.fileDate = [attributes fileModificationDate];
		}
		else {
            NSLog(@"Error while checking file attribute of : %@ [ %@ ]",filePath,error);
		}
	}
}

/*
 ------------------------------------------------------------------------
 URLCacheConnectionDelegate protocol methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark URLCacheConnectionDelegate methods

- (void) connectionDidFail:(URLCacheConnection *)theConnection
{
    NSLog(@"Connection failed!");
    //[self endLoading];
}


- (void) connectionDidFinish:(URLCacheConnection *)theConnection
{
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == YES) {
        
		/* apply the modified date policy */
        
		[self getFileModificationDate];
		NSComparisonResult result = [theConnection.lastModified compare:fileDate];
		if (result == NSOrderedDescending) {
			/* file is outdated, so remove it */
			if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]) {
                NSLog(@"Error while removing item at path : %@ [ %@ ]",filePath,error);
			}
            
		}
	}
    
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO) {
		/* file doesn't exist, so create it */
		[[NSFileManager defaultManager] createFileAtPath:filePath
												contents:theConnection.receivedData
											  attributes:nil];
        
		NSLog(@"Newly cached data because data not found in cache or new data available : %@",filePath);
        
        if(viewController) {
            NSLog(@"Update cell to display image : %@",filePath);
            UITableViewCell *cell = [viewController.tableView cellForRowAtIndexPath:news.cellIndexPath];
            NSData *data = [NSData dataWithContentsOfFile:filePath];
            cell.imageView.image = [[UIImage imageWithData:data] scaleToSize:CGSizeMake(92.0f,88.0f)];
            [viewController.tableView reloadData];
        }
        
	}
	else {
		NSLog(@"Cached data is up to date, no new data available : %@",filePath);
	}
    
	/* reset the file's modification date to indicate that the URL has been checked */
    
	NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSDate date], NSFileModificationDate, nil];
	if (![[NSFileManager defaultManager] setAttributes:dict ofItemAtPath:filePath error:&error]) {
		NSLog(@"Error while setting file attribute on : %@ [ %@ ]",filePath,error);
	}
	[dict release];
    
    //[self endLoading];
    
}


@end
